/**
 * 基于OCR的blocks数据结构分析文本布局
 * @param {Object} ocrData - Tesseract OCR识别结果，包含blocks字段
 * @returns {Object} 包含段落、行、题目类型等分析结果
 */
export const analyzeTextLayoutFromBlocks = (ocrData) => {
  if (!ocrData || !ocrData.blocks || !ocrData.blocks.length) {
    return { paragraphs: [], sectionHeaders: [], questions: [], text: "" };
  }

  const blocks = ocrData.blocks;
  const allParagraphs = [];
  const sectionHeaders = []; // 大题型标题，如"一、选择题"
  const instructionParagraphs = []; // 注意事项等说明性段落

  // 遍历所有blocks和paragraphs
  blocks.forEach((block) => {
    if (block.paragraphs) {
      block.paragraphs.forEach((paragraph) => {
        const paragraphData = {
          text: paragraph.text.trim(),
          bbox: paragraph.bbox,
          confidence: paragraph.confidence,
          lines: paragraph.lines || [],
          type: "unknown", // 将在后续分析中确定类型
        };

        // 分析段落类型
        const cleanText = paragraphData.text.replace(/\s+/g, " ");

        // 检查是否是大题型标题
        if (isSectionHeader(cleanText)) {
          paragraphData.type = "section_header";
          sectionHeaders.push(paragraphData);
        }
        // 检查是否是注意事项等说明
        else if (isInstructionText(cleanText)) {
          paragraphData.type = "instruction";
          instructionParagraphs.push(paragraphData);
        }
        // 检查是否是题目
        else if (isQuestionText(cleanText)) {
          paragraphData.type = "question";
        }
        // 检查是否是选项
        else if (isOptionText(cleanText)) {
          paragraphData.type = "option";
        } else {
          paragraphData.type = "content";
        }

        allParagraphs.push(paragraphData);
      });
    }
  });

  return {
    paragraphs: allParagraphs,
    sectionHeaders,
    instructionParagraphs,
    text: ocrData.text || "",
    confidence: ocrData.confidence || 0,
  };
};

/**
 * 检查文本是否是大题型标题（如"一、选择题"）
 */
const isSectionHeader = (text) => {
  const patterns = [
    /[一二三四五六七八九十]+\s*[、.]\s*选择题/,
    /[一二三四五六七八九十]+\s*[、.]\s*填空题/,
    /[一二三四五六七八九十]+\s*[、.]\s*解答题/,
    /[一二三四五六七八九十]+\s*[、.]\s*计算题/,
    /[一二三四五六七八九十]+\s*[、.]\s*应用题/,
    /第\s*[一二三四五六七八九十\d]+\s*[大部分]题/,
  ];

  return patterns.some((pattern) => pattern.test(text));
};

/**
 * 检查文本是否是说明性文本（注意事项等）
 */
const isInstructionText = (text) => {
  const patterns = [
    /注意\s*事项/,
    /答卷\s*前/,
    /考试\s*结束/,
    /回答\s*选择题\s*时/,
    /用\s*铅笔/,
    /答题\s*卡/,
    /试卷\s*上\s*无效/,
  ];

  return patterns.some((pattern) => pattern.test(text));
};

/**
 * 检查文本是否是题目
 */
const isQuestionText = (text) => {
  const patterns = [
    /^\d+\s*[.．、]\s*\S+/, // 以数字+标点开头的题目
    /^\(\d+\)\s*\S+/, // 以(数字)开头的题目
    /样本\s*数据/, // 具体题目内容特征
    /已知.*求/, // 数学题目特征
    /设.*则/, // 数学题目特征
  ];

  return (
    patterns.some((pattern) => pattern.test(text)) && !isInstructionText(text)
  );
};

/**
 * 检查文本是否是选项
 */
const isOptionText = (text) => {
  const patterns = [
    /^[ABCD]\s*[.．]\s*\d+/, // A. 14 B. 16 形式的选项
    /^[ABCD]\s*[.．]\s*[^\d]/, // 其他A. B. 形式的选项
  ];

  return patterns.some((pattern) => pattern.test(text));
};

/**
 * 从分析结果中提取具体题目并生成截图区域
 * @param {Object} layoutAnalysis - 布局分析结果
 * @param {Object} ocrData - 原OCR数据，用于获取图像尺寸
 * @returns {Array} 题目数组，包含题目区域和作答区域的坐标
 */
export const extractQuestionsFromBlocks = (layoutAnalysis, ocrData) => {
  const { paragraphs = [], sectionHeaders = [] } = layoutAnalysis;

  if (!paragraphs.length) {
    return [];
  }

  // 获取图像尺寸（从整个文档的边界框计算）
  const imageSize = calculateImageSize(ocrData);

  // 过滤掉注意事项等非题目内容
  const filteredParagraphs = paragraphs.filter(
    (p) => p.type !== "instruction" && p.text.trim().length > 0
  );

  // 按Y坐标排序，确保题目顺序正确
  filteredParagraphs.sort((a, b) => a.bbox.y0 - b.bbox.y0);

  const questions = [];
  let currentSection = null;

  for (let i = 0; i < filteredParagraphs.length; i++) {
    const paragraph = filteredParagraphs[i];

    // 如果是大题型标题，更新当前章节
    if (paragraph.type === "section_header") {
      currentSection = {
        title: paragraph.text,
        type: extractSectionType(paragraph.text),
        startIndex: i,
        bbox: paragraph.bbox,
      };
      continue;
    }

    // 只处理题目类型的段落
    if (paragraph.type !== "question") {
      continue;
    }

    // 提取题号
    const questionNumber = extractQuestionNumber(paragraph.text);
    if (!questionNumber) {
      continue;
    }

    // 查找该题目的选项（对于选择题）
    const options = findQuestionOptions(filteredParagraphs, i);

    // 计算题目区域和作答区域
    const questionArea = calculateQuestionArea(
      paragraph,
      options,
      filteredParagraphs,
      i,
      imageSize
    );

    const question = {
      id: questionNumber,
      text: paragraph.text.trim(),
      type: currentSection ? currentSection.type : "unknown",
      sectionTitle: currentSection ? currentSection.title : "",
      bbox: questionArea.questionBbox,
      answerArea: questionArea.answerBbox,
      options: options,
      confidence: paragraph.confidence || 0,
    };

    questions.push(question);
  }

  console.log("提取到的题目:", questions);
  return questions;
};

/**
 * 计算图像尺寸
 */
const calculateImageSize = (ocrData) => {
  if (!ocrData.blocks || !ocrData.blocks.length) {
    return { width: 1600, height: 2400 }; // 默认尺寸
  }

  let minX = Infinity,
    minY = Infinity;
  let maxX = -Infinity,
    maxY = -Infinity;

  ocrData.blocks.forEach((block) => {
    if (block.bbox) {
      minX = Math.min(minX, block.bbox.x0);
      minY = Math.min(minY, block.bbox.y0);
      maxX = Math.max(maxX, block.bbox.x1);
      maxY = Math.max(maxY, block.bbox.y1);
    }
  });

  return {
    width: maxX - minX + 100, // 加一些边距
    height: maxY - minY + 100,
  };
};

/**
 * 从章节标题中提取题目类型
 */
const extractSectionType = (sectionTitle) => {
  if (/选择题/.test(sectionTitle)) return "choice";
  if (/填空题/.test(sectionTitle)) return "fill";
  if (/解答题/.test(sectionTitle)) return "answer";
  if (/计算题/.test(sectionTitle)) return "calculate";
  if (/应用题/.test(sectionTitle)) return "application";
  return "unknown";
};

/**
 * 从题目文本中提取题号
 */
const extractQuestionNumber = (text) => {
  const patterns = [
    /^(\d+)\s*[.．、]/, // 1. 2、
    /^\((\d+)\)/, // (1) (2)
  ];

  for (const pattern of patterns) {
    const match = text.match(pattern);
    if (match) {
      return parseInt(match[1]);
    }
  }

  return null;
};

/**
 * 查找题目的选项
 */
const findQuestionOptions = (paragraphs, questionIndex) => {
  const options = [];

  // 从题目后面查找选项
  for (let i = questionIndex + 1; i < paragraphs.length; i++) {
    const paragraph = paragraphs[i];

    // 如果遇到下一个题目，停止查找
    if (paragraph.type === "question" || paragraph.type === "section_header") {
      break;
    }

    // 检查是否是选项
    if (paragraph.type === "option") {
      const optionMatch = paragraph.text.match(/^([ABCD])\s*[.．]\s*(.+)/);
      if (optionMatch) {
        options.push({
          label: optionMatch[1],
          text: optionMatch[2].trim(),
          bbox: paragraph.bbox,
        });
      }
    }
  }

  return options;
};

/**
 * 计算题目区域和作答区域
 */
const calculateQuestionArea = (
  questionParagraph,
  options,
  allParagraphs,
  questionIndex,
  imageSize
) => {
  const questionBbox = questionParagraph.bbox;

  // 查找下一个题目的位置，用于计算作答区域的下边界
  let nextQuestionY = imageSize.height;
  for (let i = questionIndex + 1; i < allParagraphs.length; i++) {
    if (
      allParagraphs[i].type === "question" ||
      allParagraphs[i].type === "section_header"
    ) {
      nextQuestionY = allParagraphs[i].bbox.y0;
      break;
    }
  }

  // 计算选项区域的下边界
  let optionsBottomY = questionBbox.y1;
  if (options.length > 0) {
    optionsBottomY = Math.max(...options.map((opt) => opt.bbox.y1));
  }

  // 题目区域：从题目开始到选项结束（如果有选项）
  const questionAreaBbox = {
    x0: Math.min(questionBbox.x0, 0),
    y0: questionBbox.y0,
    x1: Math.max(questionBbox.x1, imageSize.width),
    y1: optionsBottomY,
  };

  // 作答区域：从选项结束到下一题目开始
  const totalHeight = nextQuestionY - questionBbox.y0;
  const questionHeight = optionsBottomY - questionBbox.y0;
  const answerHeight = Math.max(totalHeight - questionHeight, 100); // 至少100像素的作答空间

  const answerAreaBbox = {
    x0: 0,
    y0: optionsBottomY + 10, // 稍微离开选项区域
    x1: imageSize.width,
    y1: optionsBottomY + answerHeight,
  };

  return {
    questionBbox: questionAreaBbox,
    answerBbox: answerAreaBbox,
  };
};

// 保持原有的analyzeTextLayout函数作为兼容
export const analyzeTextLayout = (ocrData) => {
  // 使用新的基于blocks的分析方法
  const layoutAnalysis = analyzeTextLayoutFromBlocks(ocrData);

  // 返回兼容格式
  return {
    words: [], // v6.x中没有详细的单词信息
    lines: layoutAnalysis.paragraphs.flatMap((p) => p.lines || []),
    paragraphs: layoutAnalysis.paragraphs,
    text: layoutAnalysis.text,
    confidence: layoutAnalysis.confidence || 0,
    imageWidth: 1600, // 默认值
    imageHeight: 2400, // 默认值
    sectionHeaders: layoutAnalysis.sectionHeaders,
  };
};

// 更新extractQuestions函数以支持新的分析结果
export const extractQuestions = (layoutAnalysis, ocrData = null) => {
  // 如果传入的是新的分析结果，直接使用
  if (layoutAnalysis.sectionHeaders) {
    return extractQuestionsFromBlocks(layoutAnalysis, ocrData);
  }

  // 否则使用原有的逻辑作为兼容
  const {
    lines = [],
    text = "",
    imageHeight = 600,
    imageWidth = 800,
  } = layoutAnalysis;

  if (!text || !text.trim()) {
    return createDefaultQuestions(layoutAnalysis);
  }

  const questions = [];
  const textLines = text.split("\n");

  // 提取所有以数字+句号开头的行作为题目
  const questionLines = [];

  textLines.forEach((line, index) => {
    const trimmedLine = line.trim();
    // 检查是否以数字+点号开头（如 "1. ", "2. "）
    const questionMatch = trimmedLine.match(/^(\d+)\s*\.\s*(.*)/);
    if (questionMatch) {
      questionLines.push({
        questionNumber: parseInt(questionMatch[1]),
        text: trimmedLine,
        fullText: questionMatch[2], // 题目内容（去除编号）
        lineIndex: index,
        originalLine: line,
      });
    }
  });

  console.log("找到的题目行:", questionLines);

  // 如果没有找到正常格式的题目，使用默认分割
  if (questionLines.length === 0) {
    console.log("未找到数字编号题目，使用默认分割");
    return createDefaultQuestions(layoutAnalysis);
  }

  // 按题号排序
  questionLines.sort((a, b) => a.questionNumber - b.questionNumber);

  // 为每个题目创建区域
  questionLines.forEach((questionLine, index) => {
    const currentLineIndex = questionLine.lineIndex;
    const nextQuestionLineIndex =
      index < questionLines.length - 1
        ? questionLines[index + 1].lineIndex
        : textLines.length;

    // 计算题目区域的Y坐标和高度
    const questionStartY = (currentLineIndex / textLines.length) * imageHeight;
    const questionEndY =
      (nextQuestionLineIndex / textLines.length) * imageHeight;
    const totalQuestionHeight = questionEndY - questionStartY;

    // 题干区域占30%，作答区占70%
    const questionAreaHeight = Math.max(totalQuestionHeight * 0.3, 50);
    const answerAreaHeight = Math.max(totalQuestionHeight * 0.7, 100);

    const question = {
      id: questionLine.questionNumber,
      text: questionLine.text,
      fullText: questionLine.fullText,
      bbox: {
        x: 0,
        y: questionStartY,
        width: imageWidth,
        height: questionAreaHeight,
      },
      answerArea: {
        x: 0,
        y: questionStartY + questionAreaHeight,
        width: imageWidth,
        height: answerAreaHeight,
      },
    };

    questions.push(question);
  });

  console.log("提取的题目结果:", questions);
  return questions;
};

/**
 * 创建默认题目分割（当无法识别具体题目时）
 */
const createDefaultQuestions = (layoutAnalysis) => {
  const { imageHeight = 600, imageWidth = 800, text = "" } = layoutAnalysis;

  // 如果有文本内容，基于文本内容创建题目
  if (text && text.trim()) {
    const textLines = text.split("\n").filter((line) => line.trim().length > 0);
    const lineCount = textLines.length;

    if (lineCount > 0) {
      // 根据文本行数自动分割
      const questionsPerGroup = Math.max(1, Math.floor(lineCount / 3)); // 分为3组
      const questions = [];

      for (let i = 0; i < 3; i++) {
        const startLine = i * questionsPerGroup;
        const endLine = Math.min((i + 1) * questionsPerGroup, lineCount);

        if (startLine < lineCount) {
          const questionText = textLines
            .slice(startLine, Math.min(startLine + 2, endLine))
            .join("\n");
          const y = (startLine / lineCount) * imageHeight;
          const height = ((endLine - startLine) / lineCount) * imageHeight;
          const questionAreaHeight = Math.min(height * 0.4, 100);
          const answerAreaHeight = height - questionAreaHeight;

          questions.push({
            id: i + 1,
            text: questionText || `题目 ${i + 1}`,
            bbox: {
              x: 0,
              y: y,
              width: imageWidth,
              height: questionAreaHeight,
            },
            answerArea: {
              x: 0,
              y: y + questionAreaHeight,
              width: imageWidth,
              height: Math.max(answerAreaHeight, 50),
            },
          });
        }
      }

      return questions;
    }
  }

  // 默认垂直分割
  const questionCount = 3;
  const questionHeight = imageHeight / questionCount;
  const questions = [];

  for (let i = 0; i < questionCount; i++) {
    const y = i * questionHeight;
    const questionAreaHeight = questionHeight * 0.4;
    const answerAreaHeight = questionHeight * 0.6;

    questions.push({
      id: i + 1,
      text: `题目 ${i + 1}`,
      bbox: {
        x: 0,
        y: y,
        width: imageWidth,
        height: questionAreaHeight,
      },
      answerArea: {
        x: 0,
        y: y + questionAreaHeight,
        width: imageWidth,
        height: answerAreaHeight,
      },
    });
  }

  return questions;
};
